import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, message, Select } from 'antd';
import axios from 'axios';

const { Option } = Select;

const UserTable = () => {
    const [users, setUsers] = useState([]);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [editingUser, setEditingUser] = useState(null);
    const [form] = Form.useForm();
    const [departments, setDepartments] = useState([]);

    
    useEffect(() => {
        fetchUsers();
        fetchDepartments();
    }, []);
    
    const fetchDepartments = async () => {
        try {
            const response = await axios.get('/dept/getAll'); // 假设获取部门列表的API
            setDepartments(response.data.data);
        } catch (error) {
            console.error('Error fetching departments:', error);
        }
    };
    const fetchUsers = async () => {
        try {
            const response = await axios.get('/user/getAll');
            setUsers(response.data.data);
        } catch (error) {
            console.error('Error fetching users:', error);
        }
    };

    const showModal = (user = null) => {
        setEditingUser(user);
        if (user) {
            form.setFieldsValue(user);
            form.setFieldsValue({ deptId: user.deptId.id });
        } else {
            form.resetFields();
        }
        setIsModalVisible(true);
    };

    const handleOk = async () => {
        try {
            await form.validateFields();
            const values = form.getFieldsValue();
            if (editingUser) {
                await axios.put('/user/edit', values);
                message.success('用户更新成功');
            } else {
                console.log('values', values);
                const { id, ...userWithoutId } = values;
                console.log('userWithoutId', userWithoutId);
                await axios.post('/user/add', userWithoutId);
                message.success('用户添加成功');
            }
            fetchUsers();
            setIsModalVisible(false);
        } catch (error) {
            console.error('Validation failed:', error);
        }
    };

    const handleDelete = (id) => {
        Modal.confirm({
            title: '确认删除',
            content: '确定要删除该用户吗？',
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            transitionName: 'ant-fade',
            onOk: async () => {
                try {
                    await axios.delete(`/user/delete/${id}`);
                    message.success('用户删除成功');
                    fetchUsers();
                } catch (error) {
                    console.error('删除用户时出错:', error);
                    message.error('删除用户失败');
                }
            },
            onCancel() {
                console.log('取消删除');
            },
        });
    };

    const columns = [
        {
            title: '用户名',
            dataIndex: 'name',
            key: 'name',
            width: 300,
        },
        {
            title: '密码',
            dataIndex: 'password',
            key: 'password',
            width: 300,
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            key: 'email',
            width: 300,
        },
        {
            title: '部门名称',
            key: 'deptName',
            width: 300,
            render: (text, record) => record.deptId.name, // 提取部门名称
        },
        {
            title: '操作',
            key: 'action',
            width: 300,
            render: (text, record) => (
                <span>
                    <Button type="link" onClick={() => showModal(record)}>编辑</Button>
                    <Button type="link" onClick={() => handleDelete(record.id)}>删除</Button>
                </span>
            ),
        },
    ];

    return (
        <div>
            <Button type="primary" style={{float: 'right', marginBottom: '10px'}} onClick={() => showModal()}>添加用户</Button>
            <Table dataSource={users} columns={columns} rowKey="id" />
            <Modal
                title={editingUser ? '编辑用户' : '新增用户'}
                open={isModalVisible}
                onOk={handleOk}
                onCancel={() => setIsModalVisible(false)}
                okText="提交"
                cancelText="取消"
            >
                <Form form={form} layout="vertical" style={{marginTop: '20px'}}>
                    <Form.Item name="id" label="ID" hidden={true}>
                        <Input />
                    </Form.Item>
                    <Form.Item name="name" label="用户名" rules={[{ required: true, message: '请输入用户名!' }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item name="password" label="密码" rules={[
                        { required: true, message: '请输入密码!' },
                        { min: 6, message: '密码至少6位' },
                        { max: 20, message: '密码最多20位' }
                    ]}>
                        <Input />
                    </Form.Item>
                    <Form.Item 
                        name="email"
                        label="邮箱" 
                        rules={[
                            { required: true, message: '请输入邮箱!' },
                            { type: 'email', message: '请输入有效的邮箱地址!' },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item name="deptId" label="部门" rules={[{ required: true, message: '请选择部门!' }]}>
                        <Select placeholder="请选择部门">
                            {departments.map(dept => (
                                <Option key={dept.id} value={dept.id}>{dept.name}</Option>
                            ))}
                        </Select>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default UserTable;
